<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="120px"
             status-icon>

      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="BaseInfo">
          <el-form-item label="名称：" prop="name">
            <el-input v-model="formData.name" :readonly="readonly" maxlength="64" placeholder="请输入名称" show-word-limit/>
          </el-form-item>

          <el-form-item label="级别：" prop="level">
            <el-input-number v-model="formData.level" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入级别"/>
          </el-form-item>

          <el-form-item label="级别图标：" prop="icon">
            <el-input v-model="formData.icon" :autosize="{ minRows: 1}" :disabled="readonly" placeholder="请点击上传图标" style="margin-bottom: 5px" type="textarea"/>
            <UploadImage v-model="formData.icon" :disabled="readonly" :show-delete="true"/>
          </el-form-item>

          <el-form-item label="背景图片：" prop="background">
            <el-input v-model="formData.background" :autosize="{ minRows: 1}" :disabled="readonly" placeholder="请点击上传背景图片" style="margin-bottom: 5px" type="textarea"/>
            <UploadImage v-model="formData.background" :disabled="readonly" :show-delete="true"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="权益配置" name="SoftwareConfig">
          <el-form-item label="商城让利比例：" prop="bonus_ratio">
            <el-input-number v-model="formData.bonus_ratio" :disabled="readonly" :min="0" :max="1" :precision="2" :step="0.01" controls-position="right" placeholder="请输入分润比例"/>
            <span class="tip">{{ toPercent(formData.bonus_ratio || 0.00) }} 商城订单让利部分分润占比</span>
          </el-form-item>

          <el-form-item label="本地让利比例：" prop="bonus_ratio_store">
            <el-input-number v-model="formData.bonus_ratio_store" :disabled="readonly" :min="0" :max="1" :precision="2" :step="0.01" controls-position="right" placeholder="请输入分润比例"/>
            <span class="tip">{{ toPercent(formData.bonus_ratio_store || 0.00) }} 本地订单让利部分分润占比</span>
          </el-form-item>

          <el-form-item label="提现分润比例：" prop="bonus_ratio_withdraw">
            <el-input-number v-model="formData.bonus_ratio_withdraw" :disabled="readonly" :min="0" :max="1" :precision="2" :step="0.01" controls-position="right" placeholder="请输入分润比例"/>
            <span class="tip">{{ toPercent(formData.bonus_ratio_withdraw || 0.00) }} 团队内用户提现手续费分润占比</span>
          </el-form-item>

          <el-divider border-style="dashed"/>

          <el-form-item label="开通价格：" prop="price">
            <el-input-number v-model="formData.price" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入开通价格"/>
          </el-form-item>

          <el-form-item label="粉丝开通奖励：" prop="reward">
            <el-input-number v-model="formData.reward" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入粉丝开通奖励"/>
            <span class="tip">粉丝购买该级别时候 对上级的奖励</span>
          </el-form-item>

          <el-form-item label="贡献值奖励：" prop="contribution">
            <el-input-number v-model="formData.contribution" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入贡献值奖励"/>
          </el-form-item>

          <el-form-item label="开通赠送软件：" prop="software_count">
            <el-input-number v-model="formData.software_count" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入软件赠送数量"/>
          </el-form-item>

          <el-form-item label="消费券赠送1：" prop="coupon_id">
            <el-select v-model="formData.coupon_id" :disabled="readonly" clearable placeholder="请选择消费券">
              <el-option v-for="item in couponList" :key="item.id" :label="item.title" :value="item.id"/>
            </el-select>
            <span class="tip">直接升级赠送</span>
          </el-form-item>

          <el-form-item label="消费券赠送2：" prop="coupon_id2">
            <el-select v-model="formData.coupon_id2" :disabled="readonly" clearable placeholder="请选择消费券">
              <el-option v-for="item in couponList" :key="item.id" :label="item.title" :value="item.id"/>
            </el-select>
            <span class="tip">非直接升级赠送</span>
          </el-form-item>

          <el-form-item label="软件复购限制：" prop="software_repeat_qty">
            <el-input-number v-model="formData.software_repeat_qty" :disabled="readonly" :min="0" :step="1" controls-position="right" placeholder="请输入软件复购最小数量"/>
            <span class="tip">数量 > 0 才能进行软件复购</span>
          </el-form-item>

          <el-form-item label="软件复购价格：" prop="software_price">
            <el-input-number v-model="formData.software_price" :disabled="readonly" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入软件复购价格"/>
          </el-form-item>

          <el-form-item label="申请条件描述：" prop="conditions">
            <el-input v-model="formData.conditions" :autosize="{ minRows: 2}" :disabled="readonly" placeholder="请输入申请条件文案信息" type="textarea"/>
          </el-form-item>

          <el-form-item label="升级条件描述：" prop="conditions2">
            <el-input v-model="formData.conditions2" :autosize="{ minRows: 2}" :disabled="readonly" placeholder="请输入升级条件文案信息" type="textarea"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="升级配置" name="UpgradeConfig">
          <el-form-item label="升级开关：" prop="open_upgrade">
            <el-radio-group v-model="formData.open_upgrade" :disabled="readonly">
              <el-radio-button :value="true">开启</el-radio-button>
              <el-radio-button :value="false">关闭</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="直推有效：" prop="directly_count">
            <el-input-number v-model="formData.directly_count" :disabled="readonly" :min="0" :precision="0" :step="1" controls-position="right" placeholder="请输入直推有效"/>
          </el-form-item>

          <el-form-item label="团队流水：" prop="team_consume">
            <el-input-number v-model="formData.team_consume" :disabled="readonly" :min="0" :precision="0" :step="1" controls-position="right" placeholder="请输入团队流水"/>
            <span class="tip">{{ formatNumericToWan(formData.team_consume || 0) }}</span>
          </el-form-item>

          <el-form-item label="图标显示：" prop="icon2">
            <el-input v-model="formData.icon2" :autosize="{ minRows: 1}" :disabled="readonly" placeholder="请点击上传图标" style="margin-bottom: 5px" type="textarea"/>
            <UploadImage v-model="formData.icon2" :disabled="readonly" :show-delete="true"/>
          </el-form-item>

          <el-form-item label="权益说明：" prop="upgrade_rights">
            <el-input v-model="formData.upgrade_rights" :autosize="{ minRows: 2}" :disabled="readonly" placeholder="请输入升级权益说明" type="textarea"/>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['config:user_level:create', 'config:user_level:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { UserLevelConfig, userLevelConfigInfo, userLevelConfigSaveOrUpdate } from '@/api/api-config.ts';
import { UploadImage } from '@/components/upload';
import { formatNumericToWan, toPercent } from '@/utils';
import { Coupon, couponSimpleList } from '@/api/api-coupon.ts';

defineOptions({name: 'user-level-config-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: UserLevelConfig = <UserLevelConfig>{
  id: 0, price: 0, reward: 0, bonus_ratio: 0, bonus_ratio_store: 0, bonus_ratio_withdraw: 0,
  software_repeat_qty: 0, software_price: 0, software_count: 0,
  open_upgrade: false, directly_count: 0, team_consume: 0
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  level: [{required: true, message: '级别不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

const activeName = ref();
/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '用户级别配置';
  dialogVisible.value = true;
  activeName.value = 'BaseInfo'
  // 重置表单
  handleFormReset();
  // 加载消费券信息
  await initCouponData();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await userLevelConfigInfo(id)
      formData.value = data;
      if (!formData.value.coupon_id) {
        formData.value.coupon_id = undefined;
      }
      if (!formData.value.coupon_id2) {
        formData.value.coupon_id2 = undefined;
      }
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    userLevelConfigSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 加载消费券信息 */
const couponList = ref<Coupon[]>([]);
const initCouponData = async () => {
  couponList.value = [];
  const {data} = await couponSimpleList({status: 1, valid_type: 0, deleted: 0});
  couponList.value = data;
};


</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
